package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangyoucheng
 * @date 2025/9/2
 * @description TOD0
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取请求头user-info值
        String userId    = request.getHeader("user-info");
        //绑定到当前线程上，放行
        if (StringUtils.hasText(userId)) {
            UserContext.setUser(Long.parseLong(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       UserContext.removeUser();
    }
}
